package cn.itcast.eduorder.controller;


import cn.itcast.commonutils.JwtUtils;
import cn.itcast.commonutils.R;
import cn.itcast.eduorder.entity.Order;
import cn.itcast.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Duanzihuang
 * @since 2020-06-20
 */
@Api(description = "订单管理")
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "创建订单")
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        // 1、使用JWT工具，获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        // 2、调用service实现创建订单的功能
        String orderNO = orderService.createOrder(courseId,memberId);

        return R.ok().data("orderNO",orderNO);
    }

    @ApiOperation(value = "根据订单号获取订单信息")
    @GetMapping("/getOrderInfo/{orderNO}")
    public R getOrderInfo(@PathVariable String orderNO) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_no",orderNO);

        Order orderInfo = orderService.getOne(wrapper);

        return R.ok().data("orderInfo",orderInfo);
    }

    @ApiOperation(value = "查询某个课程是否购买了")
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }
}

